package com.wc.util;

import com.wc.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;
/**
* @Description:    数工具类
* @Author:         颜升衡
* @CreateDate:     10:00 10:00
* @UpdateDate:     10:00 10:00
* @UpdateRemark:   修改内容
* @Version:        1.0
*/
public class TreeUtil {

    /**
     * 树构建
     * @param treeNodes
     * @param parentId
     * @return
     */
    public static List<TreeNode> build(List<TreeNode> treeNodes, String parentId){
        List<TreeNode> finalTreeNodes = new ArrayList<>();
        for(TreeNode treeNode : treeNodes){
            if(parentId.equals(treeNode.getParentId())){
                finalTreeNodes.add(treeNode);
                innerBuild(treeNodes,treeNode);
            }
        }
        return finalTreeNodes;
    }

    /**
     * 递归查找子节点
     * @param treeNodes
     * @param parentNode
     */
    private static void innerBuild(List<TreeNode> treeNodes,TreeNode parentNode){
        for(TreeNode childNode : treeNodes){
                if(parentNode.getId().equals(childNode.getParentId())){
                    List<TreeNode> children = parentNode.getChildren();
                    if(children == null){
                        children = new ArrayList<>();
                        parentNode.setChildren(children);
                    }
                children.add(childNode);
                childNode.setParentId(parentNode.getId());
                innerBuild(treeNodes,childNode);
            }
        }
    }

}